package com.sikaryofficial.gateway.filter;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.sikaryofficial.common.core.constant.BrandEnum;
import com.sikaryofficial.common.core.constant.CacheConstants;
import com.sikaryofficial.common.core.constant.GatewayFilterOrdered;
import com.sikaryofficial.common.core.constant.HttpStatus;
import com.sikaryofficial.common.core.constant.SecurityConstants;
import com.sikaryofficial.common.core.constant.TokenConstants;
import com.sikaryofficial.common.core.utils.JwtUtils;
import com.sikaryofficial.common.core.utils.ServletUtils;
import com.sikaryofficial.common.core.utils.StringUtils;
import com.sikaryofficial.common.core.utils.ip.IpUtils;
import com.sikaryofficial.common.redis.service.RedisService;
import com.sikaryofficial.gateway.config.properties.IgnoreWhiteProperties;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.text.MessageFormat;
import java.time.LocalDate;
import java.util.Locale;
import java.util.Objects;

/**
 * 网关鉴权
 * 
 * @author ruoyi
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered
{
    private static final Logger log = LoggerFactory.getLogger(AuthFilter.class);

    // 排除过滤的 uri 地址，nacos自行添加
    @Autowired
    private IgnoreWhiteProperties ignoreWhite;

    @Autowired
    private RedisService redisService;

    @Value("${hismk.user.ageLimit}")
    private Integer limitAge;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain)
    {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();

        String url = request.getURI().getPath();
        // 跳过不需要验证的路径
        if (StringUtils.matches(url, ignoreWhite.getWhites())) {
            // 白名单 用户ID处理
            processWhiteUri(request, mutate);
            addDayActiveByNoLogin(request);
            return chain.filter(exchange);
        }
        String token = getToken(request);
        if (StringUtils.isEmpty(token)) {
            addDayActiveByNoLogin(request);
            return unauthorizedResponse(exchange, "Token cannot be empty");
        }
        Claims claims = JwtUtils.parseToken(token);
        if (claims == null) {
            addDayActiveByNoLogin(request);
            return unauthorizedResponse(exchange, "Token has expired or verification is incorrect！");
        }
        String userkey = JwtUtils.getUserKey(claims);
        boolean islogin = redisService.hasKey(getTokenKey(userkey));
        if (!islogin) {
            addDayActiveByNoLogin(request);
            return unauthorizedResponse(exchange, "Login status has expired");
        }
        String userid = JwtUtils.getUserId(claims);
        String username = JwtUtils.getUserName(claims);
        if (StringUtils.isEmpty(userid) || StringUtils.isEmpty(username)) {
            return unauthorizedResponse(exchange, "Token verification failed");
        }
        /**
         *  日活
         */
        addDayActive(userid, request);
        /**
         * 缓存读取年龄
         */
        // 查看年龄是否满足限制
        String catchKey = MessageFormat.format(CacheConstants.USER_AGE_KEY, userid);
        Integer age = redisService.getCacheObject(catchKey);
        if (Objects.isNull(age) || age < limitAge) {
            return unauthorizedResponse(exchange, "user age verification failed");
        }
        // 设置用户信息到请求
        addHeader(mutate, SecurityConstants.USER_KEY, userkey);
        addHeader(mutate, SecurityConstants.DETAILS_USER_ID, userid);
        addHeader(mutate, SecurityConstants.DETAILS_USERNAME, username);
        // 内部请求来源参数清除
        removeHeader(mutate, SecurityConstants.FROM_SOURCE);
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }

    private void processWhiteUri(ServerHttpRequest request, ServerHttpRequest.Builder mutate) {
        // 如果是白名单地址，有传递token，需要把userId 进行头信息传递
        String token = getToken(request);
        if(CharSequenceUtil.isBlank(token)){
            return;
        }
        Claims claims = JwtUtils.parseToken(token);
        if(Objects.isNull(claims)){
            return;
        }
        String userid = JwtUtils.getUserId(claims);
        addHeader(mutate, SecurityConstants.DETAILS_USER_ID, userid);
    }

    /**
     * 设置日活
     *
     * @param userId
     */
    private void addDayActive(String userId, ServerHttpRequest request) {
        if (CharSequenceUtil.isBlank(userId)) {
            return;
        }
        // 设置日活数据，模拟用户访问后台
        try {
            String brand = request.getHeaders().getFirst(SecurityConstants.BRAND_KEY);
            if (CharSequenceUtil.isBlank(brand)) {
                brand = BrandEnum.HISMK.getCode();
            }
            // 记录明细数据 - 日期、品牌
            String catchKey1 = MessageFormat.format(CacheConstants.DAY_DETAIL_ACTIVITY_KEY, LocalDateTimeUtil.format(LocalDate.now(), "yyyyMMdd"), brand.toUpperCase(Locale.ROOT));
            redisService.addCacheSetItem(catchKey1, userId);
        } catch (Exception e) {
            log.error("设置日活异常", e);
        }
    }

    private void addDayActiveByNoLogin(ServerHttpRequest request) {
        // 设置日活数据，模拟用户访问后台
        try {
            String token = getToken(request);
            // token 非空，则不进行统计
            if (StringUtils.isNotBlank(token)) {
                return ;
            }
            String brand = request.getHeaders().getFirst(SecurityConstants.BRAND_KEY);
            String ipAddress = IpUtils.getIpAddressByGateway(request);
            if (CharSequenceUtil.isBlank(ipAddress)) {
                return;
            }
            if (CharSequenceUtil.isBlank(brand)) {
                brand = BrandEnum.HISMK.getCode();
            }
            // 记录明细数据 - 日期、品牌
            String catchKey1 = MessageFormat.format(CacheConstants.DAY_DETAIL_NO_LOGIN_ACTIVITY_KEY, LocalDateTimeUtil.format(LocalDate.now(), "yyyyMMdd"), brand.toUpperCase(Locale.ROOT));
            redisService.addCacheSetItem(catchKey1, ipAddress);
        } catch (Exception e) {
            log.error("设置日活异常", e);
        }
    }

    private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value)
    {
        if (value == null)
        {
            return;
        }
        String valueStr = value.toString();
        String valueEncode = ServletUtils.urlEncode(valueStr);
        mutate.header(name, valueEncode);
    }

    private void removeHeader(ServerHttpRequest.Builder mutate, String name)
    {
        mutate.headers(httpHeaders -> httpHeaders.remove(name)).build();
    }

    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String msg)
    {
        log.error("[鉴权异常处理]请求路径:{}", exchange.getRequest().getPath());
        return ServletUtils.webFluxResponseWriter(exchange.getResponse(), org.springframework.http.HttpStatus.UNAUTHORIZED, msg, HttpStatus.UNAUTHORIZED);
    }

    /**
     * 获取缓存key
     */
    private String getTokenKey(String token)
    {
        return CacheConstants.LOGIN_TOKEN_KEY + token;
    }

    /**
     * 获取请求token
     */
    private String getToken(ServerHttpRequest request)
    {
        String token = request.getHeaders().getFirst(TokenConstants.AUTHENTICATION);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX))
        {
            token = token.replaceFirst(TokenConstants.PREFIX, StringUtils.EMPTY);
        }
        return token;
    }

    @Override
    public int getOrder()
    {
        return GatewayFilterOrdered.AUTH;
    }
}